package com.zzcoder.mall.security.component;

import com.zzcoder.mall.common.dto.ResponseResult;
import com.zzcoder.mall.common.util.JsonUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter writer = response.getWriter();
        writer.println(JsonUtil.toJSON(ResponseResult.fail(HttpServletResponse.SC_FORBIDDEN, "权限不足")));
        writer.flush();
        writer.close();
    }
}
